using System;
using System.Collections.Generic;
using UnityEngine;

public class PoolManager : MonoBehaviour
{
    public static PoolManager Instance;
    [SerializeField] private int expansionCapacity = 5;
    private Dictionary<string, Queue<GameObject>> poolDict = new();
    private Dictionary<string, GameObject> parentTransDict = new();
    void Awake()
    {
        Instance = this;
    }
    public GameObject Get(GameObject obj, Action<GameObject> onAction = null)
    {
        string objName = obj.name;
        if (!parentTransDict.TryGetValue(objName, out var parent))
        {
            parent = new(objName);
            parentTransDict[objName] = parent;
        }
        if (!poolDict.TryGetValue(objName, out Queue<GameObject> pool))
        {
            pool = new();
            parent.transform.SetParent(transform);
            ExpandCapacity(obj, pool, parent.transform);
            poolDict[objName] = pool;
        }
        if (pool.Count == 0)
            ExpandCapacity(obj, pool, parent.transform);

        GameObject targetObject = pool.Dequeue();
        targetObject.SetActive(true);
        onAction?.Invoke(targetObject);
        return targetObject;
    }
    public void Delease(GameObject obj, Action onAction=null)
    {
        if (obj == null) return;
        string objName = obj.name.Replace("(Clone)", "").Trim();
        if (poolDict.ContainsKey(objName))
        {
            obj.SetActive(false);
            onAction?.Invoke();
            poolDict[objName].Enqueue(obj);
            return;
        }
#if UNITY_EDITOR
        Destroy(obj);
        Debug.LogError($"Can not find the object---{obj}");
#endif
    }
    
    //扩容
    private void ExpandCapacity(GameObject obj, Queue<GameObject> targetPool,Transform parent)
    {
        if (obj == null) return;
        for (int i = 0; i < expansionCapacity; i++)
        {
            GameObject instance = Instantiate(obj, transform);
            instance.gameObject.name = instance.gameObject.name.Replace("(Clone)", "").Trim();
            instance.SetActive(false);
            instance.transform.SetParent(parent);
            targetPool.Enqueue(instance);
        }
#if UNITY_EDITOR
        Debug.Log($"Success to expansionCapcity ----- {obj}");
#endif
    }
}
